package com.soujiayi.activity;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.client.ClientProtocolException;

import com.soujiayi.search.SearchSuggestion;
import com.soujiayi.store.DatabaseHelper;
import com.soujiayi.store.SPResolver;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class SearchActivity extends Activity {
	private EditText et_search_input;
	private SimpleAdapter sAdapter;
	private ListView lv_search_list;
	private View v_clear_history;
	private TextView tv_search_clearhistory;
	private List<String> historyList;
	private Button btn_search_submit;
	private boolean taskCancled = false;
	private enum SearchType {
		History, Suggestion
	}

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.search);
		initViewByOrder();
		initSearchHistory();
		initActionListener();
		lv_search_list.setAdapter(sAdapter);
	}

	public void initViewByOrder() {
		v_clear_history = getLayoutInflater().inflate(R.layout.search_footer,
				null);
		lv_search_list = (ListView) findViewById(R.id.lv_search_list);
		lv_search_list.addFooterView(v_clear_history);
		btn_search_submit = (Button)findViewById(R.id.btn_search_submit);
		tv_search_clearhistory = (TextView) v_clear_history
				.findViewById(R.id.tv_search_clearhistory);
		et_search_input = (EditText) findViewById(R.id.et_search_input);

	}

	public void initActionListener() {
		tv_search_clearhistory.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				DatabaseHelper dbhelper = new DatabaseHelper(SearchActivity.this);
				dbhelper.removeAllSearchHistory();
				initSearchHistory();
			}
		});
		btn_search_submit.setOnClickListener(new View.OnClickListener(){

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				DatabaseHelper dbhelper = new DatabaseHelper(SearchActivity.this);
				dbhelper.insertSearchHistory(et_search_input.getText().toString());
			}
			
		});
		
		et_search_input.addTextChangedListener(new TextWatcher() {
			@Override
			public void beforeTextChanged(CharSequence s, int arg1, int arg2,
					int arg3) {
			}

			@Override
			public void onTextChanged(CharSequence s, int arg1, int arg2,
					int arg3) {
				
				if ("".equals(s.toString())) {
					if (lv_search_list.getFooterViewsCount() == 0)
						taskCancled = true;
						initSearchHistory();
				} else {
					new SearchSuggestionTask().execute(s.toString());
				}
			}

			@Override
			public void afterTextChanged(Editable arg0) {
				// TODO Auto-generated method stub

			}
		});
	}

	public void initSearchHistory() {
		historyList = new ArrayList<String>();
		DatabaseHelper dbhelper = new DatabaseHelper(SearchActivity.this);
		historyList = dbhelper.getAllSearchHistory();
		updateListView(historyList, SearchType.History);
	}

	public void updateListView(List<String> list, SearchType searchType) {
		String tv_searchitem_suggest = "tv_searchitem_suggest";
		ArrayList<HashMap<String, Object>> listItem = new ArrayList<HashMap<String, Object>>();
		for (int i = 0; i < list.size(); i++) {
			HashMap<String, Object> map = new HashMap<String, Object>();
			map.put(tv_searchitem_suggest, list.get(i));
			listItem.add(map);
		}		
		sAdapter = new SimpleAdapter(this, listItem, R.layout.search_item,
				new String[] { tv_searchitem_suggest },
				new int[] { R.id.tv_searchitem_suggest });
		if (searchType.equals(SearchType.History)) {
			
			if (lv_search_list.getFooterViewsCount() == 0) {
				lv_search_list.addFooterView(v_clear_history);
			}
		} else if (searchType.equals(SearchType.Suggestion)) {
			if (lv_search_list.getFooterViewsCount() != 0) {
				lv_search_list.removeFooterView(v_clear_history);
			}
		}
		lv_search_list.setAdapter(sAdapter);
		sAdapter.notifyDataSetChanged();
	}

	@Override
	protected void onRestart() {
		// TODO Auto-generated method stub
		super.onRestart();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.search, menu);
		return true;
	}

	public class SearchSuggestionTask extends
			AsyncTask<String, Integer, List<String>> {

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			taskCancled = false;
		}

		@Override
		protected List<String> doInBackground(String... params) {
			// TODO Auto-generated method stub
			List<String> list = new ArrayList<String>();
			try {
				list = SearchSuggestion.getSuggestion(params[0]);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return list;
		}

		@Override
		protected void onPostExecute(List<String> result) {
			// TODO Auto-generated method stub
			if (taskCancled==false)
				updateListView(result, SearchType.Suggestion);
		}
	}

}
